import axios from 'axios'
import { ElMessage } from 'element-plus'
import { userLoadingStore } from '@/stores'
import VueCookie from 'vue-cookie'
import router from '@/router'

export const _axios = axios.create({
	baseURL: 'http://127.0.0.1:8081'
})

const userLoading = userLoadingStore()

// 响应过滤器
_axios.interceptors.request.use(config => {
	const token = VueCookie.get('token')
	if(token){
		//传到请求头
		config.headers.token = token
	}
	return config
},error => {
	return Promise.reject(error)
})
export const request = (url, method, params ,callback) => {
	const axiosConfig = {
		url,
		method
	}
	if (method === 'post') {
		const formData = new FormData()
		for (const key in params) {
			formData.append(key, params[key])
		}
		axiosConfig.data = formData
	} else {
		axiosConfig.params = params
	}
	userLoading.setLoading(true)
	_axios.request(axiosConfig).then(response => {
		if (response.data.code === 200) {
			if (response.data.message) {
				ElMessage.success(response.data.message)
			}
			callback(response.data.content)
		} else {
			ElMessage.error(response.data.message)
			if(response.data.code === 401){
				router.push({
					path:'/'
				})
			}
		}
	}).catch(error => {
		console.dir(error)
	}).finally(() => {
		userLoading.setLoading(false)
	})
}
export const get = (url,params,callback) => { request(url,'get',params,callback) }
export const post = (url,params,callback,formObj = null) => {
	if (formObj) {
		formObj.value.validate(valid => {
			if (valid) {
				request(url,'post',params,callback)
			}
		})
	} else {
		request(url,'post',params,callback)
	}
}
export const submitMultipleForms = async (url, params, callback, formObjs = []) => {
  try {
    let isValid = true;

    if (formObjs.length > 0) {
      // 创建一个Promise数组，用于等待所有表单验证完成
      const validationPromises = formObjs.map(formObj => {
        return new Promise(resolve => {
          formObj.value.validate(valid => {
            console.dir(valid);
            if (!valid) {
              isValid = false;
            }
            resolve(valid);
          });
        });
      });

      // 等待所有Promise完成
      await Promise.all(validationPromises);
    }

    // 所有验证都通过后，才执行请求
    if (isValid) {
      post(url, params, callback);
    }
  } catch (error) {
    console.error("Error during form validation:", error);
  }
};
